package com.arunsawad.ilertu.activity;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.adapter.RegisteredServicesAdapter;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.RightDrawableOnTouchListener;
import com.arunsawad.ilertu.common.Utils;
import com.arunsawad.ilertu.common.Validator;
import com.arunsawad.ilertu.dto.RegisteredService;

public class RegisteredServices extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	ListView listView;
	EditText txtSearch;
	private List<RegisteredService> registeredServices = new ArrayList<RegisteredService>();
	private RegisteredServicesAdapter adapter;
	int page = 0;
	ProgressDialog bar;
	Button btnLoadMore;
	private static final int GET_SERVICES = 0;
	private static final int DELETE_SERVICE = 1;
	int currentTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_registeredservices);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title1_imgbtn_txt_imgbtn);
		
		initTitle();

		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);
		Validator.Validate(this, preferences);
		txtSearch = (EditText) findViewById(R.id.registeredservices_txtSearch);

		final Drawable x = getResources().getDrawable(R.drawable.delete);

		txtSearch.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				if (txtSearch.getText().toString().equals("")) {
					txtSearch.setCompoundDrawables(null, null, null, null);
				} else {
					x.setBounds(0, 0, x.getIntrinsicWidth(),
							x.getIntrinsicHeight());
					txtSearch.setCompoundDrawables(null, null, x, null);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		txtSearch.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					page = 0;
					registeredServices = new ArrayList<RegisteredService>();
					doSearch();
					return true;
				}
				return false;
			}
		});

		txtSearch.setOnTouchListener(new RightDrawableOnTouchListener(
				txtSearch, x) {
			public boolean onDrawableTouch(final MotionEvent event) {
				txtSearch.setText("");
				txtSearch.setCompoundDrawables(null, null, null, null);
				page = 0;
				registeredServices = new ArrayList<RegisteredService>();
				doSearch();
				return false;
			}
		});
		btnLoadMore = new Button(this);

		// Getting a reference to ListView
		listView = (ListView) findViewById(R.id.lv_registeredServices);
		doSearch();
	}
	
	@SuppressWarnings("deprecation")
	public void initTitle(){
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title1_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});
		
		TextView txtTitle = (TextView) findViewById(R.id.title1_txtTitle);
		txtTitle.setText(getString(R.string.registered_services));
		
		ImageButton imgBtn2 = (ImageButton) findViewById(R.id.title1_imgBtn2);
		imgBtn2.setBackgroundDrawable(getResources().getDrawable(R.drawable.add_orange));
		imgBtn2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						Categories.class);
				startActivity(intent);
			}
		});
	}

	public void add(View view) {
		Intent intent = new Intent(getApplicationContext(), Categories.class);
		startActivity(intent);
	}

	public void doSearch() {
		// show progress bar
		bar = new ProgressDialog(RegisteredServices.this);
		bar.setIndeterminate(true);
		bar.show();

		String filter = "<keywords>";
		filter += "<serviceKeyword>"
				+ ((EditText) findViewById(R.id.registeredservices_txtSearch))
						.getText() + "</serviceKeyword>";
		filter += "<lastPageNumber>" + String.valueOf(page)
				+ "</lastPageNumber>";
		filter += "</keywords>";
		String msg = String.format(Constants.MSG, "ilertu.user.services-list",
				preferences.getString(Constants.PREF_USER_NAME, ""),
				preferences.getString(Constants.PREF_PASSWORD, ""),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), filter);

		currentTask = GET_SERVICES;
		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_GET_REGISTERED_SERVICES, msg);
	}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));

				if (currentTask == DELETE_SERVICE) {
					// delete service
					NodeList nodes = document.getElementsByTagName("error");

					if (nodes.getLength() > 0) {
						Element error = (Element) nodes.item(0);
						String message = error
								.getElementsByTagName("errorDesc").item(0)
								.getTextContent();
						Utils.alert(this, message);
					} else {
						Intent intent = new Intent(getApplicationContext(),
								RegisteredServices.class);
						startActivity(intent);
					}
				} else {
					// get registered services
					NodeList nodes = document.getElementsByTagName("service");

					// fill in the list items from the XML document
					for (int i = 0; i < nodes.getLength(); i++) {
						Element e = (Element) nodes.item(i);

						String id = e.getAttribute("id");
						String name = e.getElementsByTagName("name").item(0)
								.getTextContent();
						String imageUrl = e.getElementsByTagName("imageUrl")
								.item(0).getTextContent();
						String status = e
								.getElementsByTagName("responseStatus").item(0)
								.getTextContent();
						String permanent = e.getElementsByTagName("permanent")
								.item(0).getTextContent();
						String phone = e.getElementsByTagName("phone").item(0)
								.getTextContent();
						String siteUrl = e.getElementsByTagName("redirectUrl")
								.item(0).getTextContent();
						RegisteredService service = new RegisteredService(id,
								status, permanent, name, imageUrl, phone,
								siteUrl);
						registeredServices.add(service);
					}

					// handel more button
					if (nodes.getLength() == Constants.RECORDS_PER_PAGE) {
						if (page == 0) {
							// LoadMore button
							btnLoadMore.setText("Load More");
							btnLoadMore.setVisibility(View.VISIBLE);
							// Adding Load More button to lisview at bottom
							listView.addFooterView(btnLoadMore);

							/**
							 * Listening to Load More button click event
							 * */
							btnLoadMore
									.setOnClickListener(new View.OnClickListener() {
										@Override
										public void onClick(View arg0) {
											// Starting a new async task
											page += 1;
											doSearch();
										}
									});
						}
					} else {
						btnLoadMore.setVisibility(View.GONE);
					}

					// get listview current position - used to maintain scroll
					// position
					int currentPosition = listView.getFirstVisiblePosition();

					// create base adapter
					adapter = new RegisteredServicesAdapter(
							RegisteredServices.this, registeredServices);
					listView.setAdapter(adapter);
					listView.setSelectionFromTop(currentPosition, 0);

					// hide progress bar
					bar.hide();

					// star loading image for each service
					for (int i = (page * Constants.RECORDS_PER_PAGE); i < registeredServices
							.size(); i++) {
						registeredServices.get(i).loadImage(adapter);
					}

					listView.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							TextView txtInfo = (TextView) view
									.findViewById(R.id.registeredservices_txtHiddenInfo);
							String test = txtInfo.getText().toString();
							String[] info = test.split("\\|", 5);
							String serviceId = info[0];
							String phone = info[3];
							String siteUrl = info[4];
							if (!siteUrl.startsWith("http://")
									&& !siteUrl.startsWith("https://"))
								siteUrl = "http://" + siteUrl;
							List<String> options = new ArrayList<String>();
							if (info[1].equals("1")) {
								options.add(getString(R.string.lert));
							}
							options.add(getString(R.string.call));
							options.add(getString(R.string.view_service_info));
							options.add(getString(R.string.goto_service_site));
							if (info[2].equalsIgnoreCase("false")) {
								options.add(getString(R.string.delete));
							}
							options.add(getString(R.string.cancel));
							showAccOptions(view, serviceId, phone, siteUrl,
									options);
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void showAccOptions(View view, final String serviceId,
			final String phone, final String siteUrl, final List<String> options) {
		AlertDialog.Builder alertDialogBuilder = new Builder(this);
		alertDialogBuilder.setTitle("Options");
		CharSequence[] types = options
				.toArray(new CharSequence[options.size()]);
		alertDialogBuilder.setItems(types, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String selected = options.get(which);
				if (selected.equals(getString(R.string.lert))) {
					Intent intent = new Intent(getApplicationContext(),
							Lert.class);
					intent.putExtra("serviceId", serviceId);
					startActivity(intent);
				}
				if (selected.equals(getString(R.string.call))) {
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(Uri.parse("tel:" + phone));
					startActivity(intent);
				}
				if (selected.equals(getString(R.string.view_service_info))) {
					Intent intent = new Intent(getApplicationContext(),
							ServiceDetails.class);
					intent.putExtra("serviceId", serviceId);
					startActivity(intent);
				}
				if (selected.equals(getString(R.string.goto_service_site))) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(siteUrl));
					startActivity(intent);
				}
				if (selected.equals(getString(R.string.delete))) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							RegisteredServices.this);
					alertDialogBuilder
							.setMessage(R.string.confirm_delete_service)
							.setPositiveButton(R.string.ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											String filter = "<service id=\""
													+ serviceId + "\"/>";
											String msg = String
													.format(Constants.MSG,
															"ilertu.user.services-delete",
															preferences
																	.getString(
																			Constants.PREF_USER_NAME,
																			""),
															preferences
																	.getString(
																			Constants.PREF_PASSWORD,
																			""),
															preferences
																	.getString(
																			Constants.PREF_LANGUAGE,
																			"en"),
															filter);

											currentTask = DELETE_SERVICE;
											RequestTask task = new RequestTask();
											task.setListener(RegisteredServices.this);
											task.execute(
													Constants.URL_DELETE_SERVICE,
													msg);
										}
									})
							.setNegativeButton(R.string.cancel,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alert = alertDialogBuilder.create();
					alert.show();
				}
				if (selected.equals(getString(R.string.cancel))) {
					dialog.cancel();
				}
			}
		});
		alertDialogBuilder.show();
	}
}